import React, { PureComponent, Component } from 'react'
import { shallowEqualImmutable } from 'react-immutable-render-mixin'
import { NavigationActions, createAction, request as http } from '../utils'
import { toast } from '../utils/toast'
import * as userService from '../services/user'

class Base extends Component {
  constructor(props) {
    super(props)
    this.state = {
      fetching: false,
      notConnected: false,
      msg: null,
    }
  }
  goto = (routeName, data) => {
    const navigateAction = NavigationActions.navigate({
      routeName,
      params: data,
    })
    this.props.navigation.dispatch(navigateAction)
  }

  goBack = key => {
    this.props.navigation.dispatch(NavigationActions.back({ key }))
  }

  setParams = (key, params) => {
    const setParamsAction = NavigationActions.setParams({
      params,
      key,
    })
    this.props.navigation.dispatch(setParamsAction)
  }
  checkError(e, data) {
    if (!data) {
      data = {}
    }
    data.fetching = false
    data.refreshing = false
    if (e.code == 300) {
      // no network
      data.notConnected = true
    }

    this.setState({ ...data })
    if (!data.notConnected) {
      toast(e.msg)
    }
  }
  request = ({ url, method = 'get', data, token = true }) =>
    new Promise((resolve, reject) => {
      http({
        url,
        method,
        data,
        token,
      })
        .then(data => {
          resolve(data)
        })
        .catch(error => {
          if (error.code != 401) {
            this.setState({
              fetching: false,
              msg: error.msg,
            })
          } else {
            // sys/user/info例外
            if (url.indexOf('sys/user/info') >= 0) {
              return
            }
            // 到登录界面
            this.goto('Login')
          }
          reject(error)
        })
    })
  showModal = content => {
    this.setState({
      modalVisible: true,
      msg: content,
    })
  }
  checkLogin = async () =>
    new Promise((resolve, reject) => {
      userService
        .checkToken()
        .then(data => {
          resolve(true)
        })
        .catch(e => {
          this.goto('Login')
        })
    })
  shouldComponentUpdate = (nextProps, nextState) =>
    !shallowEqualImmutable(this.props, nextProps) ||
    !shallowEqualImmutable(this.state, nextState)
}

export default Base
